let app = getApp();
let API_URL = app.globalData.API_URL;
import importFormatTime from "../../utils/util.js";

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    postId: {
      type: Number,
      value: 0,
      observer(newVal) {
        this.setData({ postId: newVal });
        this.getComment(); // 获取评论
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    postId: 0,
    comments: [], // 评论列表
    isCommonMask: false, // 写评论对话框
    commonBTNList: [
      { id: 1, name: 'ياخشى', icon: '/common/icon/haoping.svg', ac_Icon: '/common/icon/haoping-ac.svg' },
      { id: 2, name: 'ئادەتتىكى', icon: '/common/icon/yiban.svg', ac_Icon: '/common/icon/yiban-ac.svg' },
      { id: 3, name: 'ناچار', icon: '/common/icon/chaping.svg', ac_Icon: '/common/icon/chapin-ac.svg' }
    ],
    comments: [
      { id:1, content: 'ئىنكاس يوق ~' },
    ],
    isCommonMask: false,
    commonCon: '', // 评论内容
    commonStatus: 0,
    userLikeComments: [], // 用户点赞的评论
    status: 1, // 状态
    goodReview: 0, // 好评
    poorReview: 0, // 差评论
    generallyReview: 0, // 一般评论


    pageNo: 1,
    pageSize: 20,
    totalPage: 0,
    totalCount: 0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 获取评论 comment
    getComment() {
      const { postId, pageNo, pageSize, status } = this.data;
      wx.request({
        url: `${API_URL}/comment?book_id=${postId}&pageNo=${pageNo}&pageSize=${pageSize}&status=${status}`,
        method: 'GET',
        success: res => {
          if(res.statusCode == 200) {
            // 初始化计数变量
            let goodReviewCount = 0;
            let poorReviewCount = 0;
            let generallyReviewCount = 0;

            for(let item of res.data.data) {
              item.time = importFormatTime.importFormatTime(item.releaseTime, 'h:m:s Y.M.D');
              switch (item.attitude) {
                case 1:
                  goodReviewCount++; // 好评+1
                  break;
                case 2:
                  poorReviewCount++; // 差评+1
                  break;
                case 3:
                  generallyReviewCount++; // 一般评论+1
                  break;
                default:
                  console.warn(`未知的attitude值：${item.attitude}`);
              }
            };

            // 计算总评论数
            const totalReviews = res.data.totalCount || 1; // 避免除以0（若无评论则默认1）

            // 计算各类型评价占比（保留1位小数）
            goodReviewCount = ((goodReviewCount / totalReviews) * 100).toFixed(1);
            poorReviewCount = ((poorReviewCount / totalReviews) * 100).toFixed(1);
            generallyReviewCount = ((generallyReviewCount / totalReviews) * 100).toFixed(1);

            this.setData({ 
              comments: res.data.data,
              totalPage: res.data.totalPage,
              goodReview: goodReviewCount, // 更新好评数量
              poorReview: poorReviewCount, // 更新差评数量
              generallyReview: generallyReviewCount // 更新一般评论数量
            })

            this.getUserLikeComment() // 获取点赞评论
          }
        }
      })
    },

    // 获取该用户点赞评论
    getUserLikeComment() {
      let userInfo = wx.getStorageSync('userInfo')
      if(!userInfo) return
      let that = this;
      let comments = this.data.comments; // 所有评论
      let data = { user_id: userInfo.user.id };
      wx.request({
        url: `${API_URL}/getUserLikeComment`,
        method: 'POST',
        data: data,
        header: app.header(),
        success: res => {
          if(res.statusCode == 200) {
            for (let i of comments) {
              i.isLikeComment = res.data.some(item => i.id === item.comment_id);
            }

            that.setData({ comments: comments })
          }
        }
      })
    },

    // 点赞评论
    likeComment(e) {
      let item = e.currentTarget.dataset.item;
      let userInfo = wx.getStorageSync('userInfo')
      let data = { comment_id: item.id, user_id: userInfo.user.id };
      let that = this;
      wx.request({
        url: `${API_URL}/likeComment`,
        method: 'POST',
        data: data,
        header: app.header(),
        success: res => {
          if(res.statusCode == 200) {
            that.getComment();
          }
        }
      })
    },

    // 关闭评论框
    conselCommon() {
      this.setData({ isCommonMask: false, commonStatus: 0 })
    },

    // 发送评论
    sendCommon() {
      if(this.data.commonCon == '') return this.setData({ isCommonMask: false, commonStatus: 0 })
      let user_id = wx.getStorageSync('userInfo')
      
      let data = { 
        user_id: user_id.user.id,
        book_id: this.data.postId,
        content: this.data.commonCon,
        category_id: app.globalData.kitapCon.type,
        attitude: this.data.commonStatus
      };

      let that = this;
      wx.request({
        url: `${API_URL}/comment`,
        method: 'POST',
        data: data,
        header: app.header(),
        success: res => {
          that.setData({ commonCon: '' });
          that.getComment();
          wx.showToast({
            title: 'ok ~',
            icon: 'success',
            duration: 2000
          })
        }
      })
      
      this.setData({ isCommonMask: false, commonStatus: 0 })
    },

    // 点击评论
    onCommon(item) {
      let itemId = item.currentTarget.dataset.itemid;
      if(this.data.commonStatus == 0) {
        this.setData({ isCommonMask: true, commonStatus: itemId })
      } else {
        this.setData({ commonStatus: itemId })
      }
    },

  },

  lifetimes: {
    created() {
      
    }

  }
})